import {
    Image,
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    useWindowDimensions,
    Animated,
    FlatList,
    RefreshControl, ActivityIndicator, ImageBackground, Modal, ScrollView
} from 'react-native';
import {router, Stack, useLocalSearchParams, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import {SceneMap, TabView} from "react-native-tab-view";
import * as React from "react";
import {useEffect, useState} from "react";
import icomeImage from '@/assets/images/activityImg/icomeImage.png'
import {getActivityOrderListRequest, getActivityParticipantListRequest} from "@/services/activityServices";
import { setActivityOrderDetail } from "@/store/slices/activityDetailSlice"
import {useDispatch} from "react-redux";

enum activityType {
    join,
    create,
    wait
};

const JoinRoute = ({ currentIndex }) => {
    const [pantList, setPanList] = useState([]);
    const params = useLocalSearchParams();

    useEffect(() => {
        getPantList();
    }, [])

    const getPantList = function () {
        getActivityParticipantListRequest(params.activityId)
            .then((res) => {
                setPanList(res?.data?.participant);
            })
            .catch((err) => {
                console.log('err', err);
            })
    };


   return (
       <View style={styles.registerContainer}>
           <ScrollView style={{ width: "100%", height: '100%' }}>
               <View style={styles.registerWrap}>
                   <View style={styles.registerMain}>
                       <View style={styles.mainTitleleft}>
                           <Text style={styles.mainTitleleftText}>票种名称</Text>
                       </View>
                       <View style={styles.mainTitleRight}>
                           <Text style={styles.mainTitleRightText}>报名量/名额</Text>
                       </View>
                   </View>
                   {
                       pantList.map((item: any, index: number) => {
                           return (
                               <View style={styles.TicketItem} key={index}>
                                   <View style={styles.TicketItemLeft}>
                                       <Text style={styles.TicketItemLeftText}>{ item?.ticketName }{ item.isTemporary ? "(临时票种)" : "" }</Text>
                                   </View>
                                   <View style={styles.TicketItemRight}>
                                       <Text style={styles.TicketItemRightText}>{ item?.participantNumber + " / " + item?.ticketQuantity }</Text>
                                   </View>
                               </View>
                           )
                       })
                   }

                   {/*<View style={styles.TicketItem}>*/}
                   {/*    <View style={styles.TicketItemLeft}>*/}
                   {/*        <Text style={styles.TicketItemLeftText}>临时票种（创建时间）</Text>*/}
                   {/*    </View>*/}
                   {/*    <View style={styles.TicketItemRight}>*/}
                   {/*        <Text style={styles.TicketItemRightText}>1/10</Text>*/}
                   {/*    </View>*/}
                   {/*</View>*/}
               </View>
               {
                   pantList.map((item:any, index: number) => {
                       return (
                           <View style={styles.ticketTable} key={index}>
                               <View style={styles.ticketTableTitle}>
                                   <Text style={styles.ticketTableTitleText}>{ item?.ticketName }</Text>
                               </View>
                               <View style={styles.ticketTableItemWrap}>
                                   <View style={styles.ticketTableItem}>
                                       <View style={styles.ticketTableTop}>
                                           <Text style={styles.ticketTableTopText}>已报名</Text>
                                       </View>
                                       <View style={styles.ticketTableBot}>
                                           <Text style={styles.ticketTableBotText}>{ item?.participantNumber }</Text>
                                       </View>
                                   </View>
                                   <View style={styles.ticketTableItem}>
                                       <View style={styles.ticketTableTop}>
                                           <Text style={styles.ticketTableTopText}>待审核</Text>
                                       </View>
                                       <View style={styles.ticketTableBot}>
                                           <Text style={styles.ticketTableBotText}>{ item?.pendingReviewNumber }</Text>
                                       </View>
                                   </View>
                                   <View style={styles.ticketTableItem}>
                                       <View style={styles.ticketTableTop}>
                                           <Text style={styles.ticketTableTopText}>已签到</Text>
                                       </View>
                                       <View style={styles.ticketTableBot}>
                                           <Text style={styles.ticketTableBotText}>{ item?.redeemedNumber }</Text>
                                       </View>
                                   </View>
                               </View>
                           </View>
                       )
                   })
               }
           </ScrollView>
       </View>
   )
};

const CreateRoute = ({ currentIndex }) => {
    const [orderList, setOrderList] = useState([]);

    const params = useLocalSearchParams();
    const dispatch = useDispatch();

    useEffect(() => {
        getOrderList();
    }, [])

    const getOrderList = function () {
        getActivityOrderListRequest(params.activityId)
            .then((res) => {
                setOrderList(res?.data?.order);
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    const countMoney = function () {
        let money = 0;
        orderList.forEach((item: any, index: number) => {
            money = money + item.amount;
        })
        return money;
    };

    const orderDataDetail = function (item) {
        dispatch(setActivityOrderDetail({ activityOrderDetail: item }))
        router.push("/registerGroup/orderDataDetail")
    };

    return (
        <ScrollView style={{ height: "100%", width: "100%" }}>
            <View style={styles.icomeContainer}>
                <ImageBackground source={icomeImage} style={styles.icomeHeader}>
                    <View style={styles.icomeTitle}>
                        <Text style={styles.icomeTitleText}>收入</Text>
                    </View>
                    <View style={styles.icomeMoney}>
                        <Text style={styles.icomeMoneyText}>¥{countMoney() }</Text>
                    </View>
                </ImageBackground>

                <View style={styles.icomeTableContainer}>
                    <View style={styles.icomeTableHeader}>
                        <View style={styles.time}>
                            <Text style={styles.timeText}>时间</Text>
                        </View>
                        <View style={styles.money}>
                            <Text style={styles.moneyText}>金额</Text>
                        </View>
                        <View style={styles.detail}>
                            <Text style={styles.detailText}>详情</Text>
                        </View>
                    </View>
                    {
                        orderList.map((item: any, index: number) => {
                            return (
                                <View style={styles.icomeTableBody} key={index}>
                                    <View style={styles.timeBody}>
                                        <Text style={styles.timeBodyText}>{ item?.placeTime }</Text>
                                    </View>
                                    <View style={styles.moneyBody}>
                                        <Text style={styles.moneyBodyText}>+¥{ item.amount }</Text>
                                    </View>
                                    <TouchableOpacity onPress={() => orderDataDetail(item)}>
                                        <View style={styles.detailBodt}>
                                            <Text style={styles.detailBodyText}>
                                                详情
                                            </Text>
                                            <AntDesign name="right" size={7} color="#EC6138" />
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            )
                        })
                    }
                </View>
            </View>
        </ScrollView>
    )
};

const WaitRoute = ( ) => {
    const [orderList, setOrderList] = useState([]);
    const dispatch = useDispatch();
    const params = useLocalSearchParams();

    useEffect(() => {
        getOrderList();
    }, [])

    const getOrderList = function () {
        getActivityOrderListRequest(params.activityId)
            .then((res) => {
                setOrderList(res?.data?.order);
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    const orderDataDetail = function (item) {
        dispatch(setActivityOrderDetail({ activityOrderDetail: item }))
        router.push("/registerGroup/orderDataDetail")
    };

   return (
       <ScrollView>
           <View style={styles.orderContainer}>
               {
                   orderList.map((item: any, index: number) => {
                       return (
                           <TouchableOpacity  key={index}>
                               <View style={styles.orderItem}>
                                   <View style={styles.orderHeader}>
                                       <View style={styles.orderHeaderTitle}>
                                           <Text style={styles.orderHeaderTitleText}>{ item.ticketName }</Text>
                                       </View>
                                       <View style={styles.orderHeaderMoney}>
                                           <Text style={styles.orderHeaderMoneyText}>¥{ item?.amount }</Text>
                                       </View>
                                   </View>
                                   <View style={styles.orderBody}>
                                       <View style={styles.orderUser}>
                                           <Text style={styles.orderUserText}>{ item?.userNickname }</Text>
                                       </View>
                                       <TouchableOpacity onPress={() => orderDataDetail(item)}>
                                           <View style={styles.orderLook}>
                                               <Text style={styles.orderLookText}>查看</Text>
                                               <AntDesign name="right" size={9} color="#676978" />
                                           </View>
                                       </TouchableOpacity>

                                   </View>
                               </View>
                           </TouchableOpacity>
                       )
                   })
               }
           </View>
       </ScrollView>
   )
};

// 自定义的 TabBar 组件
const CustomTabBar = ({ navigationState, position, setIndex }) => {
    // 创建指示器的动态宽度和位置
    const inputRange = navigationState.routes.map((_, i) => i);
    const layoutWith = scaleSize(350);
    const translateX = position.interpolate({
        inputRange,
        outputRange: inputRange.map(i => i * layoutWith / 3 + ((layoutWith / 3) - layoutWith / 13) / 2),
        // outputRange: [48, 162], // 这里的值需要根据实际情况计算
    });


    return (
        <View style={styles.tabHeader}>
            <View style={styles.tabBar}>
                {navigationState.routes.map((route, i) => (
                    <TouchableOpacity
                        key={route.key}
                        onPress={() => setIndex(i)}
                        style={styles.tabItem}>
                        <Text style={{ color: navigationState.index === i ? '#EC6138' : 'black', textAlign: "left" }}>
                            {route.title}
                        </Text>
                    </TouchableOpacity>
                ))}
                {/* 自定义指示器 */}
                <Animated.View
                    style={[
                        styles.indicator,
                        { transform: [{ translateX }] },
                        { width: scaleSize(26) } // 指示器的宽度
                    ]}
                />
            </View>
        </View>
    );
};


export default function activityRouteScreen() {

    const router = useRouter();
    const layout = useWindowDimensions();


    const [index, setIndex] = React.useState(0);
    const [routes] = React.useState([
            { key: 'join', title: '报名情况' },
        { key: 'create', title: '收入' },
        { key: 'check', title: '订单管理' },
    ]);

    // const renderScene = SceneMap({
    //     join: JoinRoute,
    //     create: JoinRoute,
    //     check: JoinRoute
    // });

    const renderScene = ({ route }) => {
        switch (route.key) {
            case 'join':
                return <JoinRoute currentIndex={index} key={'join'}/>; // 传递当前索引给 FirstRoute
            case 'create':
                return <CreateRoute currentIndex={index} key={'create'} />;
            case 'check':
                return <WaitRoute currentIndex={index} key={'check'} />;
            default:
                return null;
        }
    };


    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '活动数据', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#fff', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                }}
            />
            <TabView
                navigationState={{ index, routes }}
                renderScene={renderScene}
                onIndexChange={setIndex}
                initialLayout={{ width: layout.width }}
                renderTabBar={(props) => <CustomTabBar {...props} setIndex={setIndex} />} // 使用自定义的 TabBar
            />
        </View>

    );
}

const styles = StyleSheet.create({
    scene: {
        flex: 1,
        // justifyContent: 'center',
        // alignItems: 'center',
    },
    tabBar: {
        flexDirection: 'row',
        backgroundColor: 'white',
        position: 'relative', // 需要相对定位来放置指示器
        width:scaleSize(350),
        margin: "auto",
    },
    tabItem: {
        flex: 1,
        alignItems: 'center',
        paddingTop: 10,
        paddingBottom: 9,
        fontSize: 14,
        color: "#2A2B30",
    },
    indicator: {
        position: 'absolute',
        height: 3,
        backgroundColor: '#EC6138',
        bottom: 0,
        borderRadius: 5,
    },
    tabHeader: {
        backgroundColor: "#fff",
        borderBottomWidth: 1,
        borderBottomColor: "#F1F2F5",
        marginBottom: 12,
    },
    registerContainer: {
        paddingHorizontal: 12,
    },
    registerWrap: {
        backgroundColor: "#fff",
        padding: 12,
        borderRadius: 10,
    },
    registerMain: {
        flexDirection: "row",
        justifyContent: "space-between",
        borderBottomWidth: 0.5,
        borderBottomColor: "#E4E6EC",
        paddingBottom: 12,

    },
    mainTitleleft: {

    },
    mainTitleleftText: {
        fontSize: 16,
        fontWeight: "bold",
    },
    mainTitleRight: {

    },
    mainTitleRightText: {
        fontSize: 16,
        fontWeight: "bold",
    },
    TicketItem: {
        flexDirection: "row",
        justifyContent: "space-between",
        marginTop: 14,
    },
    TicketItemLeft: {

    },
    TicketItemLeftText: {
        color: "#676978",
        fontSize: 14,
    },
    TicketItemRight: {

    },
    TicketItemRightText: {
        color: "#676978",
        fontSize: 14,
    },
    ticketTable: {
        marginTop: 12,
        backgroundColor: "#fff",
        padding: 12,
        borderRadius: 10,
    },
    ticketTableTitle: {
        paddingBottom: 12,
        borderBottomWidth: 0.5,
        borderBottomColor: "#E4E6EC"
    },
    ticketTableTitleText: {
        fontSize: 16,
        color: "#2A2B30",
        fontWeight: "bold",
    },
    ticketTableItemWrap: {
        flexDirection: "row",
        justifyContent: "space-between"
    },
    ticketTableItem: {
        marginTop: 16,
        width: 70,
    },
    ticketTableTop: {

    },
    ticketTableTopText: {
        color: "#676978",
        fontSize: 14,
        textAlign: "center",
    },
    ticketTableBot: {
        marginTop: 6,
    },
    ticketTableBotText: {
        textAlign: "center",
    },
    icomeContainer: {
        paddingHorizontal: 12,
    },
    icomeHeader: {
        paddingVertical: 12,
        borderRadius: 10,
        overflow: "hidden",
    },
    icomeTitle: {

    },
    icomeTitleText: {
        textAlign: "center",
        fontSize: 14,
    },
    icomeMoney:{
        marginTop: 6,
    },
    icomeMoneyText: {
        fontSize: 28,
        color: "#EC6138",
        textAlign: "center",
    },
    icomeTableContainer: {
        marginTop: 12,
        backgroundColor: "#fff",
        padding: 12,
    },
    icomeTableHeader: {
        flexDirection: "row",
        borderBottomWidth: 0.5,
        borderBottomColor: "#E4E6EC",
        paddingBottom: 12,
        marginBottom: 16,
    },
    time: {
        flex: 1,
    },
    timeText: {
        fontWeight: "bold",
        fontSize: 16,
    },
    money: {
        width: 70
    },
    moneyText: {
        fontWeight: "bold",
        fontSize: 16,
    },
    detail: {
        width: 70
    },
    detailText: {
        textAlign: "right",
        fontWeight: "bold",
        fontSize: 16,
    },
    icomeTableBody: {
        flexDirection: "row",
        marginBottom: 16,
    },
    timeBody: {
        flex: 1,
    },
    timeBodyText: {
        color: "#676978",
        fontSize: 14,
    },
    moneyBody: {
        width: 70
    },
    moneyBodyText: {
        color: "#676978",
        fontSize: 14,
    },
    detailBodt: {
        width: 70,
        flexDirection: "row",
        justifyContent: "flex-end",
        alignItems: "center",
    },
    detailBodyText: {
        color: "#EC6138",
        fontSize: 14,
        textAlign: "right",
    },
    orderContainer: {
        paddingHorizontal: 12,

    },
    orderItem: {
        backgroundColor: "#fff",
        padding: 12,
        borderRadius: 10,
        marginBottom: 12,
    },
    orderHeader: {
        flexDirection: "row",
        justifyContent: "space-between"
    },
    orderBody: {
        flexDirection:"row",
        justifyContent: "space-between",
        marginTop: 8,
    },
    orderHeaderTitle: {},
    orderHeaderTitleText: {
        fontSize: 16,
        color: "#2A2B30"
    },
    orderHeaderMoney: {

    },
    orderHeaderMoneyText: {
        color: "#EC6138",
        fontSize: 16,
    },
    orderUser: {

    },
    orderUserText: {
        color: "#676978"
    },
    orderLook: {
        flexDirection:"row",
        alignItems: "center",
    },
    orderLookText: {
        color: "#676978",
        fontSize: 14,
    },
});
